<script lang="ts" setup>
import { ref, reactive, onBeforeMount } from 'vue'
import ReDialog from '@/components/ReDialog/index.vue'

import { _bindRole } from '@/api/user'
import { Message } from '@/utils/message'

import type { UserInfo } from '@/utils/auth'
import { _queryRoles } from '@/api/auth'

const emit = defineEmits(['afterSuccess'])
const dialogVisible = ref(false)
const title = ref('分配角色')
const formState = ref()
const roleList = ref()

onBeforeMount(() => {
  queryRoleList()
})
const show = (user: UserInfo) => {
  formState.value = {
    userId: user.id,
    roleId: user.roleId
  }
  dialogVisible.value = true
}

const handleClose = () => {
  dialogVisible.value = false
}

const submit = () => {
  _bindRole(formState.value)
    .then(res => {
      Message.success(res.message)
      emit('afterSuccess')
      handleClose()
    })
    .catch(error => {
      Message.error(error.message)
    })
}

const queryRoleList = async () => {
  _queryRoles()
    .then(res => {
      roleList.value = res.data.list
    })
    .catch(err => {
      Message.error(err.message)
    })
}

defineExpose({ show })
</script>

<template>
  <ReDialog
    v-model="dialogVisible"
    :title="title"
    @before-close="handleClose"
    @submit="submit"
  >
    <el-form
      ref="formRef"
      :model="formState"
      label-position="right"
      label-width="80px"
    >
      <el-form-item label="用户名" prop="roleId">
        <el-select v-model="formState.roleId" clearable filterable>
          <el-option
            v-for="item in roleList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
    </el-form>
  </ReDialog>
</template>
